package com.zjlanyun.eplus.view.report;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.view.report.adapter.MenuAdapter;
import com.zjlanyun.eplus.view.report.fragment.AclFragment;
import com.zjlanyun.eplus.view.report.fragment.HistogrmMainFragment;
import com.zjlanyun.eplus.view.report.fragment.ListFragment;
import com.zjlanyun.eplus.view.report.fragment.MoreChartFragment;
import com.zjlanyun.eplus.view.report.fragment.PeiMainFragment;
import com.zjlanyun.eplus.view.report.fragment.TableFragment;
import com.zjlanyun.eplus.view.report.fragment.TableLayoutFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zjlanyun.eplus.view.report.UtilConstants.ACL;
import static com.zjlanyun.eplus.view.report.UtilConstants.DEFAULT_COUNT;
import static com.zjlanyun.eplus.view.report.UtilConstants.DOUBLECHART;
import static com.zjlanyun.eplus.view.report.UtilConstants.HISTOGRM;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_NAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_MODELID;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_NAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_PROPERTYNAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_TABLENAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_TDOMAIN;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_VIEWMODE;
import static com.zjlanyun.eplus.view.report.UtilConstants.LIST;
import static com.zjlanyun.eplus.view.report.UtilConstants.PIE;
import static com.zjlanyun.eplus.view.report.UtilConstants.RECYCLEVIEW_ROWS;
import static com.zjlanyun.eplus.view.report.UtilConstants.REPORT_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_DEFAULT_LIST;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_LIST;
import static com.zjlanyun.eplus.view.report.UtilConstants.TABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.VALUE_NAME;

/**
 * 报表Activity
 *
 * @author xiao.han
 *         created at 2017/6/23 0023 14:18
 */
public class ReportActivity extends AppCompatActivity implements MenuAdapter.ItemClickListener, IFragmentImpl {
    private static final String TAG = "ReportActivity";
    private MenuAdapter myMenuAdapter; //菜单列表适配器
    public GridLayoutManager mGridLayoutManager;
    private List<Map<String, String>> mList;
    private String menuName = "";//modelid
    private String sql = "";//附加条件
    private String toolBarName = "";
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.table)
    ImageView table;
    @Bind(R.id.menu)
    RecyclerView menu;
    @Bind(R.id.fragment)
    FrameLayout fragment;

    Handler myHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //点击菜单，展示列表
                case SHOW_LIST:
                    myMenuAdapter = new MenuAdapter(mList);
                    myMenuAdapter.setOnClickListener(ReportActivity.this);
                    menu.setLayoutManager(mGridLayoutManager);
                    menu.setAdapter(myMenuAdapter);
                    break;
                //展示菜单默认选中列表
                case SHOW_DEFAULT_LIST:
                    mList.get(DEFAULT_COUNT).get(KEY_RA_VIEWMODE);
                    menuName = mList.get(DEFAULT_COUNT).get(KEY_RA_MODELID).toString();
                    sql = mList.get(DEFAULT_COUNT).get(KEY_RA_TDOMAIN).toString();
                    String name = mList.get(DEFAULT_COUNT).get(KEY_RA_NAME).toString();
                    title.setText(name);
                    switch (mList.get(DEFAULT_COUNT).get(KEY_RA_VIEWMODE)) {
                        case LIST:
                            replaceFragment(ListFragment.newInstance(menuName, sql));
                            break;
                        case HISTOGRM:
                            replaceFragment(HistogrmMainFragment.newInstance(menuName, sql));
                            break;
                        case TABLE:
                            replaceFragment(TableLayoutFragment.newInstance(menuName, sql));
                            break;
                        case PIE:
                            replaceFragment(PeiMainFragment.newInstance(menuName, sql));
                            break;
                        default:
                            Toast.makeText(ReportActivity.this, "错误！", Toast.LENGTH_SHORT);
                            break;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);
        ButterKnife.bind(this);
        initView();

    }

    /**
     * 获取数据
     */
    public void initData() {
        HttpRequest client = new HttpRequest(ReportActivity.this, WebApi.api());
        client.getRequest().add(KEY_ACTION, REPORT_ACTION);
        client.getRequest().add(KEY_NAME, VALUE_NAME);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG, "返回的数据:" + response.get().toString());
                try {
                    mList = new ArrayList<Map<String, String>>();
                    JSONObject jsonObject = new JSONObject(response.get().toString());
                    JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject myjsonObject = (JSONObject) jsonArray.get(i);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(KEY_RA_NAME, myjsonObject.optString(KEY_RA_NAME));
                        map.put(KEY_RA_MODELID, myjsonObject.optString(KEY_RA_MODELID));
                        map.put(KEY_RA_VIEWMODE, myjsonObject.optString(KEY_RA_VIEWMODE));
                        map.put(KEY_RA_TDOMAIN, myjsonObject.optString(KEY_RA_TDOMAIN));
                        mList.add(map);
                    }
                    myHandle.sendEmptyMessage(SHOW_LIST);
                    myHandle.sendEmptyMessage(SHOW_DEFAULT_LIST);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void initView() {
        //recycleView 1列
        mGridLayoutManager = new GridLayoutManager(this, RECYCLEVIEW_ROWS);
        initData();
    }

    /**
     * recycleView监听
     *
     * @param v
     * @param position
     */
    @Override
    public void onItemClick(View v, int position) {

    }

    /**
     * recycleView item监听
     *
     * @param position 位置
     * @param menuName modleId
     * @param type     布局种类
     * @param sql      sql附加条件
     * @name  name     菜单名字
     */
    @Override
    public void itemClick(int position, String menuName, String type, String sql, String name) {
        this.menuName = menuName;
        this.sql = sql;
        this.toolBarName = name;
        Log.d(TAG, "选择了位置" + position + ",名称为：" + menuName + "的菜单,布局列表为" + type + ",附加Sql语句条件:" + sql);
        title.setText(name);
        switch (type) {
            case LIST:
//                Log.d(TAG,"列表布局");
                table.setVisibility(View.GONE);
                replaceFragment(ListFragment.newInstance(menuName, sql));
                break;
            case HISTOGRM:
                table.setVisibility(View.VISIBLE);
//                Log.d(TAG,"柱形统计图");
                replaceFragment(HistogrmMainFragment.newInstance(menuName, sql));
                break;
            case TABLE:
                table.setVisibility(View.GONE);
//                Log.d(TAG,"表格布局");
                replaceFragment(TableLayoutFragment.newInstance(menuName, sql));
                break;
            case PIE:
                table.setVisibility(View.VISIBLE);
//                Log.d(TAG,"饼状统计图");
                replaceFragment(PeiMainFragment.newInstance(menuName, sql));
                break;
            case DOUBLECHART:
                table.setVisibility(View.VISIBLE);
                Log.d(TAG,"菜单名称："+name+"...菜单id："+menuName+"....sql条件："+sql);
                replaceFragment(MoreChartFragment.newInstance(menuName,sql,name));
                break;
            case ACL :
                Log.d(TAG,"新的列表布局");
                replaceFragment(AclFragment.newInstance(menuName,name));
                break;
            default:
                table.setVisibility(View.GONE);
                Toast.makeText(ReportActivity.this, "布局设置错误，请检查！", Toast.LENGTH_SHORT);
                break;
        }
    }





    /**
     * Fragment
     *
     * @param fragment 需要跳转的fragment
     */
    public void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment, fragment);
        transaction.commitAllowingStateLoss();
    }



    /**
     * 接口回调
     *
     * @param tablename    modleId
     * @param PropertyName 属性名
     */
    @Override
    public void sendMessage(String tablename, String PropertyName) {
        Log.d(TAG, "接口回调：" + tablename + "......" + PropertyName);
        Intent intent = new Intent(ReportActivity.this, TableActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KEY_RA_TABLENAME, tablename);
        bundle.putString(KEY_RA_PROPERTYNAME, PropertyName);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 监听多图标布局
     * @param modelId
     * @param sql
     */
    @Override
    public void sendModelId(String modelId, String sql , String propertyName) {
        Log.d(TAG,"sendModelId, modelId:" + modelId + ".....SQL:" + sql);
        this.menuName = modelId;
        this.sql = sql;
        this.toolBarName = propertyName;

    }

    /**
     * 顶部导航栏返回按钮以及显示表格按钮的监听
     * @param view
     */
    @OnClick({R.id.back, R.id.table})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.table:
                Log.d(TAG,"显示表格"+menuName + "////" + sql);
                //跳转Fragemnt形式的表格页面
//                replaceFragment(TableFragment.newInstance(menuName, sql));
                //跳转Activity形式的表格显示页面
                Intent intent = new Intent(ReportActivity.this, TableActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(KEY_RA_TABLENAME, menuName);
                bundle.putString(KEY_RA_PROPERTYNAME, toolBarName);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

}
